<html>
<head>

<title>Groovy Goodness: Sum the Values in a Object Array</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Sum the Values in a Object Array</h3>

<div class="post">
<p>Since Groovy 1.7.1 we can use the <code>sum()</code> method on an array of objects. We already could use it for collections and iterators, but this has been extended to array of objects. The <code>sum()</code> can take a closure as an argument. The result of the closure is used to add the values together. Finally we can use an initial value for the sum.</p>
<pre class="brush:groovy">
def n = 0..5 as Integer[]

assert n instanceof Integer[]
assert      0 + 1 + 2 + 3 + 4 + 5 == n.sum()
assert 10 + 0 + 1 + 2 + 3 + 4 + 5 == n.sum(10)
assert      0 + 10 + 20 + 30 + 40 + 50 == n.sum { it * 10 }
assert 10 + 0 + 10 + 20 + 30 + 40 + 50 == n.sum(10, { it * 10 })
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>